using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 点击消除模式 - 点击方块消除相同颜色的连通区域
/// </summary>
public class ClickEliminationMode : MonoBehaviour
{
    [Header("游戏设置")]
    public int minConnectedCount = 3; // 最少连接数量才能消除
    public float eliminationDelay = 0.1f; // 消除动画延迟
    public float fallSpeed = 5f; // 下落速度
    
    [Header("引用")]
    public GridManager gridManager;
    
    // 游戏状态
    private bool isProcessing = false;
    private Tile[,] grid;
    private int width, height;
    
    // 连通区域检测用的访问标记
    private bool[,] visited;
    
    void Start()
    {
        if (gridManager == null)
            gridManager = FindObjectOfType<GridManager>();
            
        InitializeMode();
    }
    
    /// <summary>
    /// 初始化点击消除模式
    /// </summary>
    public void InitializeMode()
    {
        if (gridManager != null)
        {
            grid = gridManager.GetGrid();
            width = gridManager.GetWidth();
            height = gridManager.GetHeight();
            visited = new bool[width, height];
            
            // 订阅瓦片点击事件
            SubscribeToTileEvents();
        }
    }
    
    /// <summary>
    /// 订阅所有瓦片的点击事件
    /// </summary>
    private void SubscribeToTileEvents()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                if (grid[x, y] != null)
                {
                    grid[x, y].OnTileSelected += OnTileClicked;
                }
            }
        }
    }
    
    /// <summary>
    /// 取消订阅瓦片事件
    /// </summary>
    private void UnsubscribeFromTileEvents()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                if (grid[x, y] != null)
                {
                    grid[x, y].OnTileSelected -= OnTileClicked;
                }
            }
        }
    }
    
    /// <summary>
    /// 处理瓦片点击事件
    /// </summary>
    /// <param name="clickedTile">被点击的瓦片</param>
    private void OnTileClicked(Tile clickedTile)
    {
        if (isProcessing || clickedTile == null || clickedTile.isEmpty)
            return;
            
        StartCoroutine(ProcessTileClick(clickedTile));
    }
    
    /// <summary>
    /// 处理瓦片点击的协程
    /// </summary>
    private IEnumerator ProcessTileClick(Tile clickedTile)
    {
        isProcessing = true;
        
        // 查找连通区域
        List<Tile> connectedTiles = FindConnectedTiles(clickedTile);
        
        // 检查是否满足消除条件
        if (connectedTiles.Count >= minConnectedCount)
        {
            // 消除连通区域
            yield return StartCoroutine(EliminateTiles(connectedTiles));
            
            // 应用重力
            yield return StartCoroutine(ApplyGravity());
            
            // 填充空位
            yield return StartCoroutine(FillEmptySpaces());
            
            // 更新分数 (点击消除模式分数更高，因为难度更大)
            GameManager.Instance.AddScore(connectedTiles.Count * 15);
        }
        else
        {
            // 提示无法消除（可以添加视觉反馈）
            Debug.Log($"连接数量不足：{connectedTiles.Count}，需要至少{minConnectedCount}个");
        }
        
        isProcessing = false;
    }
    
    /// <summary>
    /// 使用深度优先搜索查找连通区域
    /// </summary>
    /// <param name="startTile">起始瓦片</param>
    /// <returns>连通的瓦片列表</returns>
    private List<Tile> FindConnectedTiles(Tile startTile)
    {
        // 重置访问标记
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                visited[x, y] = false;
            }
        }
        
        List<Tile> connectedTiles = new List<Tile>();
        DFS(startTile.gridX, startTile.gridY, startTile.tileType, connectedTiles);
        
        return connectedTiles;
    }
    
    /// <summary>
    /// 深度优先搜索算法
    /// </summary>
    private void DFS(int x, int y, int targetType, List<Tile> connectedTiles)
    {
        // 边界检查
        if (x < 0 || x >= width || y < 0 || y >= height)
            return;
            
        // 检查是否已访问或为空或类型不匹配
        if (visited[x, y] || grid[x, y] == null || grid[x, y].isEmpty || grid[x, y].tileType != targetType)
            return;
            
        // 标记为已访问
        visited[x, y] = true;
        connectedTiles.Add(grid[x, y]);
        
        // 递归搜索四个方向
        DFS(x + 1, y, targetType, connectedTiles); // 右
        DFS(x - 1, y, targetType, connectedTiles); // 左
        DFS(x, y + 1, targetType, connectedTiles); // 上
        DFS(x, y - 1, targetType, connectedTiles); // 下
    }
    
    /// <summary>
    /// 消除瓦片的协程
    /// </summary>
    private IEnumerator EliminateTiles(List<Tile> tilesToEliminate)
    {
        // 标记为匹配状态并播放动画
        foreach (Tile tile in tilesToEliminate)
        {
            tile.SetMatched(true);
            yield return new WaitForSeconds(eliminationDelay);
        }
        
        // 等待动画播放完成
        yield return new WaitForSeconds(0.3f);
        
        // 清除瓦片
        foreach (Tile tile in tilesToEliminate)
        {
            tile.Clear();
            grid[tile.gridX, tile.gridY] = null;
        }
    }
    
    /// <summary>
    /// 应用重力效果
    /// </summary>
    private IEnumerator ApplyGravity()
    {
        bool hasMovement = true;
        
        while (hasMovement)
        {
            hasMovement = false;
            
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height - 1; y++)
                {
                    if (grid[x, y] == null && grid[x, y + 1] != null)
                    {
                        // 移动瓦片
                        Tile movingTile = grid[x, y + 1];
                        grid[x, y] = movingTile;
                        grid[x, y + 1] = null;
                        
                        // 更新瓦片的网格坐标
                        movingTile.gridX = x;
                        movingTile.gridY = y;
                        
                        // 移动到新位置
                        StartCoroutine(gridManager.MoveTileToPosition(movingTile, gridManager.GetWorldPosition(x, y)));
                        
                        hasMovement = true;
                    }
                }
            }
            
            if (hasMovement)
                yield return new WaitForSeconds(0.2f);
        }
    }
    
    /// <summary>
    /// 填充空位
    /// </summary>
    private IEnumerator FillEmptySpaces()
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = height - 1; y >= 0; y--)
            {
                if (grid[x, y] == null)
                {
                    // 创建新瓦片
                    Tile newTile = gridManager.CreateTile(x, y, Random.Range(0, 6), true);
                    grid[x, y] = newTile;
                    
                    // 订阅新瓦片的点击事件
                    newTile.OnTileSelected += OnTileClicked;
                    
                    yield return new WaitForSeconds(0.1f);
                }
            }
        }
    }
    
    /// <summary>
    /// 启用点击消除模式
    /// </summary>
    public void EnableMode()
    {
        enabled = true;
        SubscribeToTileEvents();
    }
    
    /// <summary>
    /// 禁用点击消除模式
    /// </summary>
    public void DisableMode()
    {
        enabled = false;
        UnsubscribeFromTileEvents();
    }
    
    void OnDestroy()
    {
        UnsubscribeFromTileEvents();
    }
}